package modules

import (
	"os"
	"fmt"
	"net/url"
	"net/http"
	"io/ioutil"
	"regexp"
	"github.com/robertkrimen/otto"
	"strings"
	"github.com/PuerkitoBio/goquery"
	"log"
)

/// 错误jan码存放位置
var ErrorJanPath    = ""

/// 页面搜索结果下载路径
var DownloadJanPath = ""

/// 亚马逊搜索地址
const amazonSearchUrl = "https://www.amazon.co.jp/s/field-keywords="

/// 亚马逊搜索为空的地址
const amazonSearchUnfindMsg  = "の検索に一致する商品はありませんでした"

/// 商品详细信息
type GoodsDetail struct {
	Url string `json:"Goodurl"`
	Jancode string `json:"Goodjancode"`
	Bcode string `json:"Bcode"`
	Thumb string `json:"Thumb"`
	Title string `json:"Title"`
	Cntitle string `json:"Cntitle"`
	Desc string `json:"Desc"`
	Price string `json:"Price"`
}

///// 商品列表信息
//type GoodsList struct {
//	Jancode string `json:"Jancode"`
//	Bcode string `json:"Bcode"`
//	Url string `json:"Url"`
//	Items []GoodsDetail `json:"Items"`
//}

/// 获取商品具体信息
func ParseGoodDetailInfo(url string) (GoodsDetail, bool) {
	res := GoodsDetail{
		Jancode:"",
		Bcode:"",
		Url:url,
		Title:"",
		Cntitle:"",
		Desc:"",
		Thumb:"",
		Price:"",
	}
	if strings.Contains(url, "https://www.amazon.co.jp") {
		if doc, err := goquery.NewDocument(url); err != nil {
			return res, false
		} else {
			thumb, _ := doc.Find("#imgTagWrapperId").Find("img").Attr("data-old-hires")
			title := doc.Find("#productTitle").Text()
			/// 中文翻译
			chtitle := TaranslateCn(title)
			price := doc.Find("#priceblock_ourprice").Text()
			res.Price = price
			res.Thumb =thumb
			res.Title = title
			res.Cntitle = chtitle
			return res, true
		}
	} else {
		return res, false
	}
	return res, true
}

/// 根据商品名称检索相关信息
func ParseSearchListHtmlByGoodname(word string) (GoodsDetail, bool) {

	googleTransUrl := "https://antlion.xsrv.jp/?SearchKeyword="+word+"&m=search&mode=All"

	gooditem := GoodsDetail{
		Jancode:"",
		Bcode:"",
		Url:"",
		Thumb:"",
		Title:"",
		Cntitle:"",
		Price:"",
	}

	u,_ := url.Parse(googleTransUrl)
	q := u.Query()
	u.RawQuery = q.Encode()

	if resp, err := http.Get(u.String()); err != nil {
		return gooditem, false
	} else {
		/// 判断是否已经检索到 該当する商品がありません。
		defer resp.Body.Close()

		if body, err := ioutil.ReadAll(resp.Body); err != nil {
			return gooditem, false
		} else {
			result := string(body)
			if strings.Contains(result, "該当する商品がありません。") {
				SaveSearchResult(ErrorJanPath, word, result)
				return gooditem, false
			} else {
				if doc, err := goquery.NewDocument(googleTransUrl); err == nil {
					// 获取所有图片
					isOk := false
					doc.Find("img").Each(func(i int, s *goquery.Selection) {
						if isOk {
							return
						}
						/// 标题
						title := s.Parent().Prev().Find("a").Text()
						title = strings.Replace(title, " ", "", -1)

						if title != "" {
							/// 中文翻译
							chtitle := TaranslateCn(title)
							chtitle = strings.Replace(chtitle, " ", "", -1)

							/// 缩略图
							thumb, _ := s.Attr("src")

							/// bcode
							bcode   := ""
							jancode := ""
							s.Parent().Next().Find("ul").Find("li").Each(func(li int, liselection *goquery.Selection) {
								listr := liselection.Text()
								listr = strings.Replace(listr, " ", "", -1)
								/// 提取bcode
								if strings.Contains(listr, "ASINコード") {
									bcode = strings.Replace(listr, "ASINコード：", "", -1)
								}
								/// 提取jancode
								if strings.Contains(listr, "JANコード") {
									jancode = strings.Replace(listr, "JANコード：", "", -1)
								}
							})

							/// 商品链接
							goodurl, err := s.Parent().Next().Find("ul").Find("li").Last().Find("input").Attr("onclick")

							/// 商品价格
							price := ""

							if err {
								goodurl = strings.Replace(goodurl, "window.open('", "", -1)
								goodurl = strings.Replace(goodurl, "')", "", -1)
								goodurl = "https://"+goodurl
								detailinfo, err := ParseGoodDetailInfo(goodurl)
								if err {
									price = detailinfo.Price
								}
							} else {
								goodurl = ""
							}

							/// 获取商品价格
							gooditem.Bcode = bcode
							gooditem.Jancode = jancode
							gooditem.Url = goodurl
							gooditem.Thumb = thumb
							gooditem.Cntitle = chtitle
							gooditem.Title = title
							gooditem.Price = price

							fmt.Println("\n 亚马逊Bcode" + gooditem.Bcode + "\n 链接: " + gooditem.Url + "\n 缩略图：" + gooditem.Thumb + " \n 标题：" + gooditem.Title + "（" + gooditem.Cntitle + "）\n 价格：" + gooditem.Price)

							if gooditem.Title != "" {
								isOk = true
							}
						}
					})
					return gooditem, true
				} else {
					return gooditem, false
				}
			}
		}
	}
}

/// 根据jancode检索相关信息
func ParaseSearchListHtmlByJancode(word string, url string) (GoodsDetail, bool) {
	doc, err := goquery.NewDocument(url)

	gooditem := GoodsDetail{
		Jancode:"",
		Bcode:"",
		Url:"",
		Thumb:"",
		Title:"",
		Cntitle:"",
		Price:"",
	}

	if err == nil {
		// Find the review items
		isOK := false
		doc.Find(".s-result-item").Each(func(i int, s *goquery.Selection) {
			if isOK {
				return
			}
			/// 亚马逊bcode
			bcode, _ := s.Attr("data-asin")

			/// 亚马逊jancode
			jancode := ""
			/// 查找jan_code
			if bcode != "" {
				if info, status := ParseSearchListHtmlByGoodname(bcode); status {
					jancode = info.Jancode
				}
			}

			/// 缩略图
			item := s.Find(".s-item-container .a-spacing-base .a-section").Find("a")

			/// 获取详情链接
			goodurl, _ := item.Attr("href")

			/// 获取缩略图
			thumb, _ := item.Find("img").Attr("src")

			/// 标题
			title, _ := item.Find("img").Attr("alt")

			/// 中文标题
			cntitle := ""
			if title != "" {
				/// 中文翻译
				cntitle = TaranslateCn(title)
			}

			/// 商品价格 多种套餐多种单价
			prices := []string{}
			s.Find(".a-spacing-mini").Eq(1).Find(".a-spacing-none").Each(func(ii int, priceselection *goquery.Selection) {
				/// 过滤价格 去除 空格 含有 ￥
				price_tmp := priceselection.Find(".a-color-price").Text()
				if price_tmp != "" && strings.Contains(price_tmp, "￥") {
					price_tmp = strings.Replace(price_tmp, " ", "", -1)
					price_tmp = strings.Replace(price_tmp, ",", "",-1)
					price_tmp = strings.Replace(price_tmp, "￥", "",-1)
					prices = append(prices, price_tmp)
				}
			})

			/// 获取商品价格
			gooditem.Bcode = bcode
			gooditem.Jancode = jancode
			gooditem.Url = goodurl
			gooditem.Thumb = thumb
			gooditem.Cntitle = cntitle
			gooditem.Title = title
			gooditem.Price = strings.Join(prices, ",")

			fmt.Println("\n 亚马逊Bcode" + gooditem.Bcode + "\n 链接: " + gooditem.Url + "\n 缩略图：" + gooditem.Thumb + " \n 标题：" + gooditem.Title + "（" + gooditem.Cntitle + "）\n 价格：" + gooditem.Price)

			if gooditem.Title != "" {
				isOK = true
			}
		})
		return gooditem, true
	}
	return gooditem, false
}

/// 文本相似度匹配
func MatchText(str_a string, str_b string) float32 {
	return float32(1)
}

/// 中文翻译
func GetTaranslateTKK(str string) (string, string) {
	googleTransUrl := "https://translate.google.cn/#ja/zh-CN/"+str
	u,_ := url.Parse(googleTransUrl)
	q := u.Query()
	u.RawQuery = q.Encode()

	request, err :=http.NewRequest("GET", u.String(),nil)
	request.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36")
	//res,_ := http.Get(u.String())
	if err != nil {
		panic(err)
	}

	client := http.Client{}

	response, _ := client.Do(request)

	result, _ := ioutil.ReadAll(response.Body)

	defer response.Body.Close()

	//defer res.Body.Close()
	/// 提取 TKK
	if string(result) == "" {
		return "", ""
	} else {
		fmt.Println(u.String())
		/// 正则 \[\[\["(.*?)\"
		digitsRegexp := regexp.MustCompile(`TKK=eval(.*?)\);`)
		JSStrs := digitsRegexp.FindString(string(result))
		VM := otto.New()
		value, err := VM.Run(JSStrs)
		if err == nil {
			tkk := value.String()

			log.Println(str)
			log.Println(tkk)

			newvalue, err := VM.Run(`
				var b=function(a,b){for(var d=0;d<b.length-2;d+=3){var c=b.charAt(d+2),c="a"<=c?c.charCodeAt(0)-87:Number(c),c="+"==b.charAt(d+1)?a>>>c:a<<c;a="+"==b.charAt(d)?a+c&4294967295:a^c}return a};var tk=function(a,TKK){for(var e=TKK.split("."),h=Number(e[0])||0,g=[],d=0,f=0;f<a.length;f++){var c=a.charCodeAt(f);128>c?g[d++]=c:(2048>c?g[d++]=c>>6|192:(55296==(c&64512)&&f+1<a.length&&56320==(a.charCodeAt(f+1)&64512)?(c=65536+((c&1023)<<10)+(a.charCodeAt(++f)&1023),g[d++]=c>>18|240,g[d++]=c>>12&63|128):g[d++]=c>>12|224,g[d++]=c>>6&63|128),g[d++]=c&63|128)}a=h;for(d=0;d<g.length;d++){a+=g[d],a=b(a,"+-a^+6")}a=b(a,"+-3^+b+-f");a^=Number(e[1])||0;0>a&&(a=(a&2147483647)+2147483648);a%=1000000;return a.toString()+"."+(a^h)};tk(
				"`+str+`","`+ tkk +`");
			`)
			if err == nil {
				return newvalue.String(), strings.Replace(u.String(), "https://translate.google.cn/#ja/zh-CN/", "", -1)
			}
		}
		return "", ""
	}
}
func TaranslateCn(str string) string {
	tkk, encodestr := GetTaranslateTKK(str)
	log.Println(tkk)
	if tkk != ""  {
		googleTransUrl := "https://translate.google.cn/translate_a/single?client=t&sl=ja&tl=zh-CN&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&source=btn&ssel=0&tsel=0&kc=1&tk="+tkk+"&q="+encodestr
		log.Println(googleTransUrl)
		res,_ := http.Get(googleTransUrl)
		result, _ := ioutil.ReadAll(res.Body)
		defer res.Body.Close()
		if string(result) == "" {
			return ""
		} else {
			/// 正则 \[\[\["(.*?)\"
			digitsRegexp := regexp.MustCompile(`\[\[\["(.*?)\"`)
			matchStrs := digitsRegexp.FindString(string(result))
			/// 过滤
			if matchStrs != "" {
				matchStrs = strings.Replace(matchStrs, `[[["`, ``, -1)
				matchStrs = strings.Replace(matchStrs, `"`, ``, -1)
				matchStrs = strings.Replace(matchStrs, " ", "", -1)
			}
			return matchStrs
		}
	} else {
		return ""
	}
}

/// 判断文件是否存在
func Exists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil { return true, nil }
	if os.IsNotExist(err) { return false, nil }
	return true, err
}

/// 保存文件
func SaveSearchResult(path string, keyword string, info string) {
	fileName := path + keyword + ".html"
	dstFile,err := os.Create(fileName)
	if err!=nil{
		fmt.Println(err.Error())
		return
	}
	defer dstFile.Close()
	dstFile.WriteString(info)
}